package com.saifan.wyy_ov.ui.communitycenter;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.saifan.wyy_ov.MyApp;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.ImgUtil;
import com.saifan.wyy_ov.utils.PictureUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import lomasky.ma.utils.SharedPrefUtil;


/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-11 17:33:29
 * @descrption 账号设置
 */

public class UserInfoActivity extends BaseActivity {
    private Toolbar toolbar;
    private EditText WYKHDAKHYHM;
    private EditText WYKHDALC;
    private EditText WYKHDAKHMC;
    private EditText WYKHDAWXH;
    private EditText WYKHDASJ;
    private EditText WYKHDADZ;
    private ImageView WYKHDATXLJ;


    private static final int HEAD_PHOTO_CHANGE = 123;
    private ArrayList<String> selectList = new ArrayList<>();
    private final int SELECT_IMG = 0;
    private final int SELECT_PHOTO_TAKEPHOTO = 4;
    private String picName = "";
    private int selectPostion = 0;
    private int PHOTO_REQUEST_CUT = 5;
    private Bitmap photo;

    List<RoomInfoBean> roomInfoBeans = new ArrayList<>();
    RoomInfoBean roomInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBeans = new Gson().fromJson(SharedPrefUtil.getString(this, "roomInfos", ""), new TypeToken<List<RoomInfoBean>>() {
        }.getType());
        setContentView();

    }

    public void setContentView() {
        setContentView(R.layout.activity_user_info);
        this.WYKHDATXLJ = (ImageView) findViewById(R.id.WYKHDA_TXLJ);
        this.WYKHDASJ = (EditText) findViewById(R.id.WYKHDA_SJ);
        this.WYKHDAWXH = (EditText) findViewById(R.id.WYKHDA_WXH);
        this.WYKHDAKHMC = (EditText) findViewById(R.id.WYKHDA_KHMC);
        if (getRoomInfoBean().getUserType() == 2)
            WYKHDAKHMC.setEnabled(true);
        else
            WYKHDAKHMC.setEnabled(false);
        this.WYKHDALC = (EditText) findViewById(R.id.WYKHDA_LC);
        this.WYKHDAKHYHM = (EditText) findViewById(R.id.WYKHDA_KHYHM);
        this.WYKHDADZ = (EditText) findViewById(R.id.WYKHDA_DZ);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        roomInfoBean = getRoomInfoBean();
        if (getRoomInfoBean().getUserType() == 2) {
            findViewById(R.id.address).setVisibility(View.VISIBLE);
            ((EditText) findViewById(R.id.WYKHDA_DZ)).setText(getRoomInfoBean().getWYFJDA_FJMC());
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_OK);
        finish();

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (roomInfoBean != null) {
            WYKHDASJ.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_SJ()));
            if (getRoomInfoBean().getUserType() == 2)
                WYKHDASJ.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_KHYHM()));
            WYKHDAWXH.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_WXH()));
            WYKHDAKHMC.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_KHMC()));
            WYKHDALC.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_LC()));
            WYKHDAKHYHM.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_KHYHM()));
            if (!StringUtil.isNullOrEmpty(roomInfoBean.getWYKHDA_TXLJ())) {
                ImgUtil.DisPlayImg(getRoomInfoBean().getWYKHDA_TXLJ(), WYKHDATXLJ, this);
            }
        }


    }

    public void editUserInfo(View view) {
        if (getRoomInfoBean().getUserType() == 3) {
            ToastUtil.showToast(this, "您的权限不能进行此操作");
            return;
        }
        if (isEmpty(WYKHDALC)) {
            ToastUtil.showToast(this, "昵称为空");
            return;
        }


        try {
            GetData getData = new GetData();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserName", getRoomInfoBean().getWYKHDA_KHYHM());
            jsonObject.put("NickName", WYKHDALC.getText().toString().trim());
            jsonObject.put("WeChatID", WYKHDAWXH.getText().toString().trim());
            if (getRoomInfoBean().getUserType() == 2) {
                jsonObject.put("Address", WYKHDADZ.getText().toString().trim());
                jsonObject.put("Name", WYKHDAKHMC.getText().toString().trim());
            }
            String method = Api.Customer.EDIT_USER_INFO;
            if (getRoomInfoBean().getUserType() == 2)
                method = Api.Customer.EDITUSERINFOTOURIST;

            getData.getDataJson(this, method, jsonObject, "正在提交", new ResponseData() {
                @Override
                public void onSuccess(String json) {
                    ToastUtil.showToast(UserInfoActivity.this, "资料已更新成功");
                    if (roomInfoBeans != null) {
                        for (int i = 0; i < roomInfoBeans.size(); i++) {
                            if (roomInfoBeans.get(i).getWYKHDA_ZJ().equals(roomInfoBean.getWYKHDA_ZJ())) {
                                roomInfoBeans.get(i).setWYKHDA_LC(WYKHDALC.getText().toString().trim());
                                roomInfoBeans.get(i).setWYKHDA_WXH(WYKHDAWXH.getText().toString().trim());

                                SharedPrefUtil.putString(UserInfoActivity.this, "roomInfos", new Gson().toJson(roomInfoBeans));
                                break;
                            }

                        }
                    }
                    roomInfoBean.setWYKHDA_LC(WYKHDALC.getText().toString().trim());
                    roomInfoBean.setWYKHDA_WXH(WYKHDAWXH.getText().toString().trim());

                    setRoomInfoBean(roomInfoBean);


                    finish();


                }

                @Override
                public void onFailed(String str) {
                    ToastUtil.showToast(UserInfoActivity.this, "资料更新失败，请检查网络后重试！");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }


    //修改头像
    public void editHeadPhoto(View view) {
        if (getRoomInfoBean().getUserType() == 3) {
            ToastUtil.showToast(UserInfoActivity.this, "您的权限不能进行此操作");
            return;
        }
        showSelectImgDialog(false, 0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_user_info, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            if (getRoomInfoBean().getUserType() == 3) {
                ToastUtil.showToast(UserInfoActivity.this, "您的权限不能进行此操作");
                return true;
            }
            startActivity(ChangePWDActivity.class);
            return true;
        } else {
            setResult(RESULT_OK);
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    public void selectImg() {
        storePermission(SELECT_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_IMG) {

                this.selectList = data.getStringArrayListExtra("data");
                if (!selectList.isEmpty()) {
                    startPhotoZoom(Uri.fromFile(new File(PictureUtil.getCompressBitmap(selectList.get(0)))));
                }


            } else if (requestCode == SELECT_PHOTO_TAKEPHOTO) {

                Bitmap bitmap = data.getParcelableExtra("data") ;
                File file = FileUtils. bitmapToFile(bitmap);
                FileUtils.toAlbum(this,file);
                picName=file.getAbsolutePath();
                if (!StringUtil.isNullOrEmpty(picName)) {
                    startPhotoZoom(Uri.fromFile(new File(PictureUtil.getCompressBitmap(picName))));
                }


            } else if (requestCode == PHOTO_REQUEST_CUT) {

                if (data != null) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        photo = bundle.getParcelable("data");

                        WYKHDATXLJ.setImageBitmap(photo);
                        uploadPhoto();
                    }


                }

            }
        }

    }

    private void uploadPhoto() {
        GetData getData = new GetData();
        RequestParams params = new RequestParams();
        String method = Api.Customer.EDIT_HEAD_PHOTO;
        if (getRoomInfoBean().getUserType() == 2) {
            method = Api.Customer.EDITHEADPHOTOTOURIST;
        }

        params.addBodyParameter(Api.Customer.UserName, getRoomInfoBean().getWYKHDA_KHYHM());
        try {
            params.addBodyParameter("photo", FileUtils.saveImageToSD(this, MyApp.AppFile + FileUtils.getPhotoFileName(), photo, 100, false));
        } catch (IOException e) {
            e.printStackTrace();
        }

        getData.getData(method, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                            String code = jsonObject.getString("Code");
                            if (code.equals("200")) {
                                String s = jsonObject.getString("Content");
                                List<String> json = new Gson().fromJson(s, new TypeToken<List<String>>() {
                                }.getType());
                                if (json.size() > 0) {
                                    if (roomInfoBeans != null) {
                                        for (RoomInfoBean infoBean : roomInfoBeans) {
                                            infoBean.setWYKHDA_TXLJ(json.get(0));

                                        }



                                        SharedPrefUtil.putString(UserInfoActivity.this, "roomInfos", new Gson().toJson(roomInfoBeans));

                                    }


                                    if (roomInfoBeans != null) {
                                        for (int i = 0; i < roomInfoBeans.size(); i++) {
                                            if (roomInfoBeans.get(i).getWYKHDA_ZJ().equals(roomInfoBean.getWYKHDA_ZJ())) {
                                                roomInfoBeans.get(i).setWYKHDA_TXLJ(json.get(0));

                                                SharedPrefUtil.putString(UserInfoActivity.this, "roomInfos", new Gson().toJson(roomInfoBeans));
                                                break;
                                            }

                                        }
                                    }

                                    ImgUtil.DisPlayImg(json.get(0), WYKHDATXLJ, UserInfoActivity.this);

                                    roomInfoBean.setWYKHDA_TXLJ(json.get(0));
                                    setRoomInfoBean(roomInfoBean);

                                    Intent intent = new Intent();
                                    intent.putExtra("data", roomInfoBean);
                                    setResult(RESULT_OK, intent);


                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }
                }

        );
    }

    //显示选择图片的对话框

    private void showSelectImgDialog(boolean hasDelete, final int deletePostion) {
        String[] items;
        items = new String[]{"从相册中选择", "拍照"};
        AlertDialog dialog = new AlertDialog.Builder(UserInfoActivity.this)
                .setTitle("选择图片")

                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            selectImg();
                        } else {
                            cammerPermission(SELECT_PHOTO_TAKEPHOTO);

                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    public void cammerPermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, position);
                return;
            } else {



                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            }
        } else {


            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


        }

    }

    public void storePermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, position);
                return;
            } else {
                Intent intent = new Intent(this, PhotoAlbumActivity.class);
                intent.putExtra("isSingle", true);

                intent.putStringArrayListExtra("data", selectList);
                startActivityForResult(intent, SELECT_IMG);
            }
        } else {
            Intent intent = new Intent(this, PhotoAlbumActivity.class);
            intent.putStringArrayListExtra("data", selectList);
            intent.putExtra("isSingle", true);
            startActivityForResult(intent, SELECT_IMG);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用摄像头", Toast.LENGTH_SHORT)
                        .show();

            }
        } else {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                this.startActivityForResult(intent, SELECT_IMG);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用本地存储读写", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }
}
